package offer;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

public class SpinLockDemo {
    // 原子引用线程
    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public void myLock() {
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName() + "\t come in");
        while (!atomicReference.compareAndSet(null, thread)) {
        }
    }

    public void myUnlock() {
        Thread thread = Thread.currentThread();
        atomicReference.compareAndSet(thread, null);
        System.out.println(thread.getName() + "\t unlock");
    }

    public static void main(String[] args) throws InterruptedException {
        SpinLockDemo demo = new SpinLockDemo();
        new Thread(() -> {
            try {
                demo.myLock();
                TimeUnit.SECONDS.sleep(5);
                demo.myUnlock();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "thread1").start();

        TimeUnit.SECONDS.sleep(1);

        new Thread(() -> {
            demo.myLock();
            demo.myUnlock();
        }, "thread2").start();
    }
}
